package com.tian.interceptor;

import com.alibaba.fastjson.JSON;
import com.tian.config.RedisConfig;
import com.tian.entity.User;
import com.tian.enums.ResultCode;
import com.tian.exception.BusinessException;
import com.tian.util.StringUtil;
import com.tian.util.UserCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2022年11月01日 17:24
 * <p>
 * 日志切面
 */
@Aspect
@Component
@Slf4j
public class LoginCheckAspect {
    @Resource
    private RedisConfig redisConfig;

    /**
     * 这里我们使用注解的形式
     * 当然，我们也可以通过切点表达式直接指定需要拦截的package,需要拦截的class 以及 method
     * 切点表达式:   execution(...)
     */
    @Pointcut("@annotation(com.tian.annotation.LoginCheckAnnotation)")
    public void webLog() {

    }

    /**
     * 接口请求参数、相应参数、耗时、路径等信息打印
     */
    @Before("webLog()")
    public void logBefore(JoinPoint joinPoint) {
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String authorization = request.getHeader("Authorization");
        if (!StringUtil.isBlank(authorization)) {
            String cache = redisConfig.get(authorization);
            if(StringUtil.isEmpty(cache)){
                throw new BusinessException(ResultCode.UNAUTHORIZED);
            }
            User user = JSON.parseObject(cache, User.class);
            UserCacheUtil.setUser(user);
        }
    }
}
